package org.example.C3p0;

//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

//获取连接池对象
//这种懒汉模式也可用枚举实现，底层基本相同，习惯使用class
public class MyC3p0 {

    //数据源对象
    private ComboPooledDataSource dataSource;

    //防止用new创建对象
    private MyC3p0() {
        dataSource = new ComboPooledDataSource();
        FileInputStream fileInputStream = null;
        try {
            //读取外部资源的对象
            Properties properties = new Properties();
            fileInputStream = new FileInputStream("D:\\program\\ProgramOfIdea\\MavenOfMysql\\src\\main\\resources\\db" +
                    ".properties");
            properties.load(fileInputStream);

            dataSource.setDriverClass(properties.getProperty("jdbcDriver"));
            dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
            dataSource.setUser(properties.getProperty("userName"));
            dataSource.setPassword(properties.getProperty("password"));
            dataSource.setMaxIdleTime(Integer.parseInt(properties.getProperty("maxIdleTime")));

            dataSource.setMaxPoolSize(Integer.parseInt(properties.getProperty("maxPoolSize")));
            dataSource.setMinPoolSize(Integer.parseInt(properties.getProperty("minPoolSize")));
            dataSource.setInitialPoolSize(Integer.parseInt(properties.getProperty("initialPoolSize")));
        } catch (IOException | PropertyVetoException e) {
            e.printStackTrace();
        }

    }

    //静态内部类
    private static class Holder {
        private static MyC3p0 myC3p0 = new MyC3p0();
    }

    //获取单例的静态函数
    public static MyC3p0 getInstance() {
        return MyC3p0.Holder.myC3p0;
    }

    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
}